<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="p">
          <el-form-item label="文章分类">
            <el-select
              v-model="p.cate_id"
              placeholder="请选择分类"
              size="small"
            >
              <el-option
                v-for="item in list"
                :key="item.id"
                :label="item.cate_name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px">
            <el-select v-model="p.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="filterArt"
              >筛选</el-button
            >
            <el-button type="info" size="small" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button
          @click="artVisible = true"
          type="primary"
          size="small"
          class="btn-pub"
          >发表文章</el-button
        >
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="tableList" border style="width: 100%">
        <el-table-column label="文章标题">
          <template v-slot="{ row }">
            <el-link type="primary" @click="getArtInfo(row.id)">
              {{ row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="cate_name" label="分类"> </el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="scope">
            {{ matDate(scope.row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
              <el-button type="danger" size="mini" @click="delArt(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <el-dialog
        title="提示"
        :visible.sync="artVisible"
        width="30%"
        fullscreen
        :before-close="handleClose"
      >
        <el-form :model="artForm" :rules="artRules" ref="artForm">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="artForm.title"></el-input>
          </el-form-item>
          <el-form-item label="文章类别" prop="cate_id">
            <el-select
              v-model="artForm.cate_id"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in list"
                :key="item.id"
                :value="item.id"
                :label="item.cate_name"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <quill-editor v-model="artForm.content"></quill-editor>
          </el-form-item>
          <el-form-item label="文章封面">
            <!-- 用来显示封面的图片 -->
            <img :src="dynamicImg" alt="" class="cover-img" ref="imgRef" />
            <br />
            <!-- 文件选择框，默认被隐藏 -->
            <input
              type="file"
              style="display: none"
              accept="image/*"
              ref="iptFile"
              @change="selectImg"
            />
            <!-- 选择封面的按钮 -->
            <el-button type="text" @click="$refs.iptFile.click()"
              >+ 选择封面</el-button
            >
          </el-form-item>
          <el-form-item prop="state">
            <el-button type="success" @click="submitClick('已发布')"
              >发布</el-button
            >
            <el-button @click="submitClick('草稿')">存为草稿</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="dialogVisible" width="80%">
      <h1 class="title">{{ artInfoList.title }}</h1>

      <div class="info">
        <span>作者：{{ artInfoList.nickname || artInfoList.username }}</span>
        <span>发布时间：{{ matDate(artInfoList.pub_date) }}</span>
        <span>所属分类：{{ artInfoList.cate_name }}</span>
        <span>状态：{{ artInfoList.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <img
        :src="'http://www.liulongbin.top:3008' + artInfoList.cover_img"
        alt=""
      />

      <div v-html="artInfoList.content"></div>
    </el-dialog>
  </div>
</template>

<script>
import { list, addArt, listTable, artInfo, delArtInfo } from 'network/login'
import defaultImg from 'assets/images/cover.jpg'
import dayjs from 'dayjs'

export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      // 脱离绑定
      p: {
        cate_id: '',
        state: ''
      },
      dynamicImg: defaultImg,
      artVisible: false,
      artForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: null,
        state: ''
      },
      artRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '文章标题的长度为1-30个字符',
            trigger: 'blur'
          }
        ],
        cate_id: [
          { required: true, message: '请输入文章类别', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ],
        cover_img: [
          { required: true, message: '请选择文章封面', trigger: 'blur' }
        ]
      },
      list: [],
      tableList: [],
      total: 0,
      artInfoList: [],
      dialogVisible: false
    }
  },
  methods: {
    // 发起网络请求获取文章分类列表
    async getList () {
      const { data: res } = await list()
      this.list = res.data
    },
    // 关闭发布页面
    async handleClose (done) {
      const reslove = await this.$confirm('确认关闭？').catch((e) => e)
      if (reslove === 'confirm') return done()
    },
    // 选择图片
    selectImg (e) {
      const files = e.target.files
      if (files.length === 0) {
        this.artForm.cover_img = null
        this.dynamicImg = defaultImg
        return
      }
      this.artForm.cover_img = files[0]
      // 方法一:
      this.dynamicImg = URL.createObjectURL(files[0])
      // 方法二:
      // const fr = new FileReader()
      // fr.readAsDataURL(files[0])
      // fr.onload = (e) => {
      //   this.dynamicImg = e.target.result
      // }
    },
    // 发布
    submitClick (state) {
      this.$refs.artForm.validate(async (valid) => {
        if (!valid) return
        this.artForm.state = state
        const fs = new FormData()
        for (const key in this.artForm) {
          fs.append(key, this.artForm[key])
        }
        const { data: res } = await addArt(fs)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.artVisible = false
        this.$refs.artForm.resetFields()
        this.dynamicImg = defaultImg
        this.getTable()
      })
    },
    // 获取文章的列表数据
    async getTable () {
      const { data: res } = await listTable(this.q)
      if (res.code === 0) {
        this.tableList = res.data
        this.total = res.total
      }
    },
    // 格式化日期
    matDate (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    // 渲染的条数发生变化时
    handleSizeChange (size) {
      this.q.pagesize = size
      this.getTable()
    },
    // 当前页发生变化时
    handleCurrentChange (val) {
      this.q.pagenum = val
      this.getTable()
    },
    // 筛选
    filterArt () {
      this.q.pagenum = 1
      for (const key in this.p) {
        this.q[key] = this.p[key]
      }
      this.getTable()
    },
    // 重置
    reset () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.p = {
        cate_id: '',
        state: ''
      }
      this.getTable()
    },
    // 根据 Id 获取文章详情
    async getArtInfo (id) {
      const { data: res } = await artInfo({ id })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.artInfoList = res.data
      this.dialogVisible = true
    },
    // 删除
    delArt (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await delArtInfo({ id })
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.tableList.length === 1) this.q.pagenum > 1 && this.q.pagenum--
        this.getTable()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  created () {
    this.getList()
    this.getTable()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}

/deep/ .ql-editor {
  min-height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
